<template>
    <el-drawer
        v-model="isShow"
        size="50%"
        :destroy-on-close="true"
        @close="closeHandle"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
        </template>

        <el-form :model="form" label-width="auto" label-position="right" ref="formRef" :rules="rules">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="案件名称" required prop="name">
                        <el-input v-model="form.name" placeholder="请输入案件名称"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="案件编号">
                        <el-input v-model="form.casecode" placeholder="请输入案件编号"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="案由" >
                        <el-cascader
                        clearable
                            v-model="form.brief"
                            :options="briefList"
                            @change="handleChange"
                            :show-all-levels='false'
                            :props="{ value: 'casebriefId', label: 'name', children: 'children' }"
                            />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="案件类别">
                        <el-select v-model="form.casetype" clearable>
                            <el-option
                                v-for="item in nj_anjian_type"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="办案单位" required prop="unitId">
                        <el-tree-select
                            v-model="form.unitId"
                            :data="deptOptionsUnit"
                            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                            value-key="deptId"
                            placeholder="选择办案单位"
                            check-strictly
                            clearable
                            default-expand-all
                            @change="handleUnitChange"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="办案部门" required prop="depid">
                        <el-tree-select
                            v-model="form.depid"
                            :data="deptOptions"
                            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                            value-key="deptId"
                            placeholder="选择上级部门"
                            check-strictly
                            clearable
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="承办人" >
                        <!-- <el-input v-model="form.adduserId"/> -->
                        <el-input v-model="userName" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="isAdd">
                    <el-form-item label="状态" required>
                        <el-select v-model="form.state">
                            <el-option
                                v-for="item in filteredSendPoliceType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-else>
                    <el-form-item label="状态" required>
                        <el-select v-model="form.state">
                            <el-option
                                v-for="item in nj_anjian_status"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="submitHandle">提交</el-button>
            <el-button @click="isShow = false">关闭</el-button>
        </template>
    </el-drawer>
</template>

<script setup>
import {getCurrentInstance} from "vue";
import {createCaseInfo, editCaseInfo,getCaseInfoInfo} from "@/api/CaseInfo/CaseInfo";
import { listDept, } from "@/api/system/dept";
import { getUserProfile } from "@/api/system/user";
const {proxy} = getCurrentInstance()
import {getCaseBirefList} from "@/api/casebiref";
const {sys_normal_disable, nj_anjian_type,nj_anjian_status} = proxy.useDict('sys_normal_disable', 'nj_anjian_type', 'nj_anjian_status')

  // 计算属性过滤字典数据
  const filteredSendPoliceType = computed(() => {
  return nj_anjian_status.value.filter(item => item.value == 1 || item.value == 2);
});
// 是否显示抽屉
const isShow = ref(false)
// 抽屉标题
const title = ref('')
// 所属单位
const deptOptions = ref([]);
const deptOptionsUnit = ref([]);

const rules = {
    name: [{ required: true, message: "案件名称不能为空", trigger: "blur" }],
    unitId: [{ required: true, message: "办案单位不能为空", trigger: "blur" }],
    depid: [{ required: true, message: "办案部门不能为空", trigger: "blur" }],
}

const userName = ref('')
const birefListV = ref([]);
const isAdd = ref(true)

const briefList = ref([])
const form = ref({
    name: '',    
    casecode: '',
    brief: '',
    acceptnumber:'',
    casetype:'',
    adduserId:'',
    depid:null,
    unitId:'',
    state: '1',
})
// 通知事件
const emit = defineEmits(['getCaseList'])


const changeShowStatus = () => {
    isShow.value = !isShow.value
}
const handleUnitChange = (newValue) => {
    form.value.depid = ""
    listDept().then(res => {
        deptOptions.value = res.data.filter(item => 
        !item.isUnit && item.parentId === newValue
    )
    })
}

onMounted(() => {
    getBiref()   //获取案由列表
})
const getBiref = async () => {
    const CaseBirefListqueryParams ={name:""}
    const pagingV ={pageNum: 1,pageSize: 999}
    
    await getCaseBirefList(CaseBirefListqueryParams,pagingV).then(res => {
        res.rows.sort((a, b) => {
        return parseInt(a.code.replace(/^0+/, ''), 10) - parseInt(b.code.replace(/^0+/, ''), 10);
      });
        birefListV.value = res.rows       //将这个值保存下来后面编辑的时候要用
        const codeLength = res.rows.filter(item => item.code.length === 2);
        const codeLength2 = res.rows.filter(item => item.code.length > 2);
        const codeLengthMap = new Map();
        codeLength.forEach(item => {
            codeLengthMap.set(item.code, { ...item, children: [] });
        });
        codeLength2.forEach(item => {
            const parentCode = item.code.substring(0, 2); // 假设 codeLength2 中的 code 的前两位是 codeLength 中的 code
            if (codeLengthMap.has(parentCode)) {
                codeLengthMap.get(parentCode).children.push(item);
            }
        });
        const result = Array.from(codeLengthMap.values());
        briefList.value = result
    })
}
// 获取单位tree数据
const getDepartment = async () => {
    await listDept().then(res => {
        const data = res.data;
        deptOptions.value = data.filter(item => !item.isUnit && item.parentId === form.value.unitId);
        deptOptionsUnit.value = proxy.handleTree(data.filter(item => item.isUnit), "deptId");
    })
}
const getUserInfo = async () => {
    // 获取个人信息-
    await getUserProfile().then(res => {
        form.value.unitId = res.data.unitId
        form.value.depid = res.data.deptId
        form.value.adduserId = res.data.userId
        userName.value = res.data.userName
        getDepartment()
    })
    
}

const showAddEditCase = () => {
    title.value = '新增案件';
    isAdd.value = true
    getUserInfo()
    changeShowStatus()
}

const showEditCase = async (data) => {
    title.value = '修改案件信息'
    isAdd.value = false
    // 对传过来的案由中文进行查找出其对应的casebriefId值
    await getCaseInfoInfo(data.caseCaseinfoId).then(res => {
            form.value = res.data
            getDepartment()
        })
    await getUserProfile().then(res => {
    userName.value = res.data.userName
    getDepartment()
    })
    changeShowStatus()
}

defineExpose({showAddEditCase,showEditCase})


const handleChange = (value) => {
    // 取最后一位
    if(value){
        const lastValue = value[value.length - 1];
        form.value.brief = lastValue
    }
}

const submitHandle = async () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            if (form.value['caseCaseinfoId']) {
                editCaseInfo(form.value).then(res => {
                    changeShowStatus()
                    emit('getCaseList', '来了老弟')
                })
            } else {
                createCaseInfo(form.value).then(res => {
                    changeShowStatus()
                    emit('getCaseList', '来了老弟')
                })
            }
        }
    });
}

// 关闭后的回调事件
const closeHandle = () => {
    form.value = {
        name:'',
        brief:'',
        casecode:'',
        casetype:'',
        acceptnumber:'',
        state:'1'
    }
    console.log(123123)
}
</script>

<style lang="scss" scoped>
h4{margin: 10px 0;}
:deep() .el-date-editor {
  width: 100%;
}
:deep() .el-cascader{width: 100%;}
</style>